package com.hotline.monitor.service.skill;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hotline.monitor.constant.Constants;
import com.hotline.monitor.dto.SkillWaitNumParamDTO;
import com.hotline.monitor.dto.SkillWaitNumRequestDTO;
import com.hotline.monitor.enums.ReturnCodeEnum;
import com.hotline.monitor.util.HttpUtils;
import com.hotline.monitor.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
@Slf4j
public class QueueDeviceServiceImpl implements QueueDeviceService {

    private static final String URI_QUEUE_DEVICE_WAIT_NUM = "/agentgateway/resource/queuedevice/{}/waitnum";

    private static final String URI_QUEUE_DEVICE_SKILL_WAIT_NUM = "/agentgateway/resource/queuedevice/{}/skillwaitnum/{}";

    private static final String URI_QUEUE_DEVICE_QUERY_ACD_STAT = "/agentgateway/resource/queuedevice/{}/queryacdstat";

    @Value("${agent.worknumber}")
    private String workNumber;

    @Value("${org.queue.default}")
    private String orgQueueDefault;

    @Value("${org.queue.12366}")
    private String orgQueue12366;

    @Value("${org.queue.12345}")
    private String orgQueue12345;

    @Value("${hotline.url}")
    private String url;

    @Override
    public Integer getQueueDeviceWaitNum() {

        String reqUrl = url + URI_QUEUE_DEVICE_WAIT_NUM;

        reqUrl = StringUtils.format(reqUrl,workNumber);

        Map<String, String> header = new HashMap<>();
        header.put("Guid", Constants.HEADER_GUID);

        String resultString = HttpUtils.doGet(reqUrl,null,header);

        log.info("查询排队信息返回：{}",resultString);

        if(StringUtils.isNotBlank(resultString)){
            JSONObject jsonObject = JSONObject.parseObject(resultString);
            if(ReturnCodeEnum.SUCCESS.getCode().equals(jsonObject.getString("retcode"))){
                Integer num = jsonObject.getInteger("result");
                return num;
            }
        }
        return 0;
    }

    /**
     * 获取指定技能队列排队总人数
     * @return
     */
    @Override
    public List<SkillWaitNumRequestDTO> getQueueDeviceSkillWaitNum() {

        List<SkillWaitNumRequestDTO> list = new ArrayList<>();

        if(StringUtils.isNotBlank(orgQueueDefault)){
            List<SkillWaitNumParamDTO> paramList = JSONObject.parseArray(orgQueueDefault,SkillWaitNumParamDTO.class);

            if(!CollectionUtils.isEmpty(paramList)){

                Map<String, String> header = new HashMap<>();
                header.put("Guid", Constants.HEADER_GUID);

                for(SkillWaitNumParamDTO skillWaitNumParamDTO : paramList) {
                    //机构代码相应的排队数
                    String orgId = skillWaitNumParamDTO.getOrgId();

                    //查询每个技能队列的排队数
                    for(Integer queue : skillWaitNumParamDTO.getQueue()){

                        SkillWaitNumRequestDTO skillWaitNumRequestDTO = new SkillWaitNumRequestDTO();
                        skillWaitNumRequestDTO.setOrgId(orgId);
                        skillWaitNumRequestDTO.setQueue(queue);
                        skillWaitNumRequestDTO.setWaitNum(0);

                        String reqUrl = url + URI_QUEUE_DEVICE_SKILL_WAIT_NUM;
                        reqUrl = StringUtils.arrayFormat(reqUrl,new String[]{workNumber,String.valueOf(queue)});

                        String resultString = HttpUtils.doGet(reqUrl,null,header);
                        log.info("查询排队信息返回：reqUrl:{},resultString:{}",reqUrl,resultString);
                        if(StringUtils.isNotBlank(resultString)){
                            JSONObject jsonObject = JSONObject.parseObject(resultString);
                            if(ReturnCodeEnum.SUCCESS.getCode().equals(jsonObject.getString("retcode"))){
                                Integer waitNum = jsonObject.getInteger("result");
                                if(waitNum > 0){
                                    skillWaitNumRequestDTO.setWaitNum(waitNum);
                                }
                            }
                        }
                        list.add(skillWaitNumRequestDTO);
                    }
                }
            }
        }
        return list;
    }

    /**
     * 查询一组技能队列统计信息
     *
     * @return
     */
    @Override
    public List<SkillWaitNumRequestDTO> getQueueDeviceQueryAcdStat() {

        return getQueueDeviceQueryAcdStat(orgQueueDefault);
    }

    /**
     * 查询12366技能队列统计信息
     *
     * @return
     */
    @Override
    public List<SkillWaitNumRequestDTO> getQueueDeviceQueryAcdStat12366() {

        return getQueueDeviceQueryAcdStat(orgQueue12366);
    }

    /**
     * 查询12345技能队列统计信息
     *
     * @return
     */
    @Override
    public List<SkillWaitNumRequestDTO> getQueueDeviceQueryAcdStat12345() {

        return getQueueDeviceQueryAcdStat(orgQueue12345);
    }

    /**
     * 查询一组技能队列统计信息
     *
     * @return
     */
    public List<SkillWaitNumRequestDTO> getQueueDeviceQueryAcdStat(String skillQueues) {

        List<SkillWaitNumRequestDTO> list = new ArrayList<>();

        if(StringUtils.isNotBlank(skillQueues)){
            List<SkillWaitNumParamDTO> skillParamList = JSONObject.parseArray(skillQueues,SkillWaitNumParamDTO.class);

            if(!CollectionUtils.isEmpty(skillParamList)){

                Map<String, String> header = new HashMap<>();
                header.put("Guid", Constants.HEADER_GUID);

                List<List<SkillWaitNumParamDTO>> partitionList = ListUtil.partition(skillParamList,50);
                Map<Integer,Integer> deviceQueueSize = new HashMap<>();

                for(List<SkillWaitNumParamDTO> paramList : partitionList){
                    //所有的技能队列
                    List<Integer> allSkills = new ArrayList<>();
                    for(SkillWaitNumParamDTO skillWaitNumParamDTO : paramList) {
                        if(!CollectionUtils.isEmpty(skillWaitNumParamDTO.getQueue())){
                            allSkills.addAll(skillWaitNumParamDTO.getQueue());
                        }
                    }
                    if(CollectionUtils.isEmpty(allSkills)){
                        return list;
                    }

                    String reqUrl = url + URI_QUEUE_DEVICE_QUERY_ACD_STAT;
                    reqUrl = StringUtils.arrayFormat(reqUrl,new String[]{workNumber});
                    //技能组参数
                    Map<String,List> skillsParam = new HashMap<>();
                    skillsParam.put("skills",allSkills);

                    //查询一组技能队列统计信息
                    String resultString = HttpUtils.doPostJson(reqUrl,JSONObject.toJSONString(skillsParam),header);
                    log.info("查询排队信息返回：resultString:{}",resultString);

                    //结果为空直接返回
                    if(StringUtils.isBlank(resultString)){
                        return list;
                    }
                    JSONObject jsonObject = JSONObject.parseObject(resultString);
                    //请求结果失败，直接返回
                    if(!ReturnCodeEnum.SUCCESS.getCode().equals(jsonObject.getString("retcode"))){
                        return list;
                    }

                    //每个队列的排队数，放入deviceQueueSize中
                    JSONArray jsonArray = jsonObject.getJSONArray("result");
                    if(!CollectionUtils.isEmpty(jsonArray)){
                        for(Object object : jsonArray){
                            JSONObject obj = (JSONObject)object;
                            deviceQueueSize.put(obj.getInteger("deviceNo"),obj.getInteger("queueSize"));
                        }
                    }
                }

                for(SkillWaitNumParamDTO skillWaitNumParamDTO : skillParamList) {
                    for(Integer queue : skillWaitNumParamDTO.getQueue()){
                        SkillWaitNumRequestDTO skillWaitNumRequestDTO = new SkillWaitNumRequestDTO();
                        skillWaitNumRequestDTO.setOrgId(skillWaitNumParamDTO.getOrgId());
                        skillWaitNumRequestDTO.setQueue(queue);

                        skillWaitNumRequestDTO.setWaitNum(Objects.isNull(deviceQueueSize.get(queue)) ? 0 : deviceQueueSize.get(queue));

                        list.add(skillWaitNumRequestDTO);
                    }
                }
            }
        }
        return list;
    }
}
